package gl.android.biyiqing;

import gl.API;
import gl.android.biyiqing.bean.Result;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.AndroidUtil;
import gl.uitls.MD5;
import gl.uitls.TextUtil;
import gl.uitls.Tip;
import gl.view.CountDownTextView;
import gl.view.SimpleDataPickerDialog;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class RegistActivity extends BYQBaseActivity {

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
	public static final String EXTRA_personnumber = "com.example.android.authenticatordemo.extra.personnumber";
	public static final String EXTRA_TIME = "com.example.android.authenticatordemo.extra.TIME";
	public static final String EXTRA_CREATER = "com.example.android.authenticatordemo.extra.EXTRA_CREATER";
	public static final String EXTRA_TITLE = "com.example.android.authenticatordemo.extra.EXTRA_TITLE";
	public static final String EXTRA_CARDID = "com.example.android.authenticatordemo.extra.EXTRA_CARDID";
	public static final String EXTRA_TEL = "com.example.android.authenticatordemo.extra.EXTRA_TEL";

	public String IMEI = AndroidUtil.getIMEI();

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserChangePassWord mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String old = "";
	private String name = "";

	private String mPassword = "";

	// UI references.
	private EditText oldView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private String codeId;
	private String tel;

	// Content View Elements

	private LinearLayout activity_regist_scroll;
	private LinearLayout content;
	private EditText regist_email;
	private EditText regist_phone;
	private EditText regist_code;
	private TextView regist_send_code;
	private EditText regist_pass;
	private TextView regist_show_pass;
	private EditText regist_nick;
	private TextView regist_birth;
	private RadioGroup radioGroup1;
	private RadioButton radio0;
	private RadioButton radio1;
	private TextView login_login_btn;
	private TextView regist_submit_btn;

	// End Of Content View Elements

	private void bindViews() {

		activity_regist_scroll = (LinearLayout) findViewById(R.id.activity_regist_scroll);
		content = (LinearLayout) findViewById(R.id.content);
		regist_email = (EditText) findViewById(R.id.regist_email);
		regist_phone = (EditText) findViewById(R.id.regist_phone);
		regist_code = (EditText) findViewById(R.id.regist_code);
		regist_send_code = (TextView) findViewById(R.id.regist_send_code);
		regist_pass = (EditText) findViewById(R.id.regist_pass);
		regist_show_pass = (TextView) findViewById(R.id.regist_show_pass);
		regist_nick = (EditText) findViewById(R.id.regist_nick);
		regist_birth = (TextView) findViewById(R.id.regist_birth);
		radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
		radio0 = (RadioButton) findViewById(R.id.radio0);
		radio1 = (RadioButton) findViewById(R.id.radio1);
		login_login_btn = (TextView) findViewById(R.id.login_login_btn);
		regist_submit_btn = (TextView) findViewById(R.id.regist_submit_btn);
		mLoginFormView = findViewById(R.id.activity_regist_scroll);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_regist_byq);
		bindViews();
		oldView = (EditText) findViewById(R.id.oldpw);

		mPasswordView = regist_email;
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							doreg();
							return true;
						}
						return false;
					}
				});

		regist_submit_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				reg();
			}
		});
		regist_send_code.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				checkTel();
			}
		});
		final SimpleDataPickerDialog simpleDataPickerDialog = new SimpleDataPickerDialog(RegistActivity.this, 0,
				new DatePickerDialog.OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker arg0, int year,
							int month, int day) {
						regist_birth.setText("" + year + "-"
								+ (month + 1) + "-" + day);
					}
				}, 0, 0, 0);
		regist_birth.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				simpleDataPickerDialog.show();
			}
		});
		regist_show_pass.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				if (regist_pass.getTransformationMethod() instanceof PasswordTransformationMethod) {
					// 设置密码可见
					regist_pass
							.setTransformationMethod(HideReturnsTransformationMethod
									.getInstance());
				} else {
					// 设置密码隐藏
					regist_pass
							.setTransformationMethod(PasswordTransformationMethod
									.getInstance());
				}
				if (regist_pass.getText() != null) {
					regist_pass.setSelection(regist_pass.getText().length());
				}

			}
		});
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void doreg() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		oldView.setError(null);

		// Store values at the time of the login attempt.
		old = oldView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(old)) {
			oldView.setError(getString(R.string.error_field_required));
			focusView = oldView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserChangePassWord();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserChangePassWord {

		public void execute(Void void1) {
			BaseControl.get(API.URL
					+ "Resetpassword?userid=%s&id=%s&code=%s&pwd=%s",
					new AjaxCallBack<String>() {
						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							mAuthTask = null;
							showProgress(false);
							Result userList2 = new Gson().fromJson(t,
									new TypeToken<Result>() {
									}.getType());
							if (!TextUtils.isEmpty(userList2.getMsg())
									&& "2".equals(userList2.getMsg())) {
								Tip.showTipDialog(RegistActivity.this,
										"修改成功,请重新登陆", "提示",
										new OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												finish();
												Intent intent = new Intent(
														RegistActivity.this,
														LoginActivity.class);
												intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
												startActivity(intent);
											}
										});
							} else if (!TextUtils.isEmpty(userList2.getMsg())
									&& "0".equals(userList2.getMsg())) {
								Tip.show("验证码不正确 ");
							} else if (!TextUtils.isEmpty(userList2.getMsg())
									&& "1".equals(userList2.getMsg())) {
								Tip.show("验证码过期（180s）");
							}
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							mAuthTask = null;
							showProgress(false);
							mPasswordView.setError(t.getMessage() + "");
							mPasswordView.requestFocus();
						}
					}, name, codeId, old, MD5.md5(mPassword));

		}
	}

	private CountDownTimer countDownTextView;

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (countDownTextView != null) {
			countDownTextView.cancel();
		}

	}

	void checkTel() {
		if (regist_phone.getText() != null
				&& TextUtil.isMobileNO(regist_phone.getText().toString())) {
			BaseControl.get(API.URL + "CheckRegtel?tel=%s",
					new AjaxCallBack<String>() {
						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							Result userList2 = new Gson().fromJson(t,
									new TypeToken<Result>() {
									}.getType());
							if (!TextUtils.isEmpty(userList2.getMsg())
									&& "2".equals(userList2.getMsg())) {
								Tip.show("验证码已发送");
								countDownTextView = new CountDownTextView(
										regist_send_code, 180 * 1000, 1000)
										.start();
							} else if (!TextUtils.isEmpty(userList2.getMsg())
									&& "0".equals(userList2.getMsg())) {
								Tip.show("手机已存在 ");
							} else if (!TextUtils.isEmpty(userList2.getMsg())
									&& "1".equals(userList2.getMsg())) {
								Tip.show("验证码发送失败");
							}
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							showProgress(false);
							oldView.setError(t.getMessage() + "");
							oldView.requestFocus();
						}
					}, regist_phone.getText());
		} else {
			Tip.show("请输入正确的手机号码");
		}

	}

	/**
	 * 邮箱，密码，昵称，性别(1男，2女 )，生日
	 */
	String data = "";

	void reg() {
		if (regist_email.getText() == null
				|| !TextUtil.isEmail(regist_email.getText().toString())) {
			Tip.show("请填写正确的邮箱");
			return;
		}
		if (TextUtils.isEmpty(regist_code.getText())) {
			Tip.show("请输入验证码");
			return;
		}
		if (TextUtils.isEmpty(regist_nick.getText())) {
			Tip.show("请输入昵称");
			return;
		}
		if (TextUtils.isEmpty(regist_birth.getText())) {
			Tip.show("请输入出生年月");
			return;
		}
		if (TextUtils.isEmpty(regist_phone.getText())) {
			Tip.show("请输入手机号码");
			return;
		}
		String sex = radio0.isChecked()?"1":"2";
		//data=邮箱，密码，昵称，性别(1男，2女 )，生日
		data = String.format("%s,%s,%s,%s,%s", regist_email.getText(), MD5.md5(regist_pass.getText().toString()),regist_nick.getText(), sex, regist_birth.getText());
		BaseControl.get(API.URL + "CheckTelCodeAndReg?tel=%s&code=%s&data=%s",
				new AjaxCallBackProxy() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						Result userList2 = new Gson().fromJson(t,
								new TypeToken<Result>() {
								}.getType());

						// 0： data数据格式不正确 1：邮箱已经存在，2：验证码不存在 3： 验证码過期 4：用户注册失败
						// 5：用户注册成功
						if (!TextUtils.isEmpty(userList2.getMsg())
								&& "5".equals(userList2.getMsg())) {
							Tip.show("注册完成");
							try {
								UserManger.getInstance().userid= new JSONObject(t).opt("userid").toString();
							} catch (JSONException e) {
								e.printStackTrace();
							}
							UserManger.getInstance().username = regist_nick.getText().toString();
							UserManger.getInstance().password = MD5.md5(regist_pass.getText().toString());
							AndroidUtil.saveToSharePreferences(LoginActivity.key_USERNAME, "0",
									UserManger.getInstance().username);
							AndroidUtil.saveToSharePreferences(LoginActivity.key_PASSWORD, "0",
									UserManger.getInstance().password);
							AndroidUtil.saveToSharePreferences("isAutoLogin", "0", "true");
							completeUserInfo();
						} else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "0".equals(userList2.getMsg())) {
							Tip.show("数据格式不正确 ");
						} else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "1".equals(userList2.getMsg())) {
							Tip.show("邮箱已经存在");
						} else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "2".equals(userList2.getMsg())) {
							Tip.show(" ：验证码不存在");
						} else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "3".equals(userList2.getMsg())) {
							Tip.show(" 验证码過期");
						}
						else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "4".equals(userList2.getMsg())) {
							Tip.show("用户注册失败");
						}
						else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "6".equals(userList2.getMsg())) {
							Tip.show("用户名存在");
						}
						else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "7".equals(userList2.getMsg())) {
							Tip.show("手机号码");
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						showProgress(false);
						Tip.show(""+t.getMessage() );
					}
				}, regist_phone.getText(), regist_code.getText(), data);

	}
	private void completeUserInfo() {
		startActivity(new Intent(this,CompleteUserInfoActivity.class));
		finish();
	}
	

}
